package com.kuang.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author Administrator
 * @date 2021/5/28 14:44
 * Description:
 */
public class CASDemo2 {
    public static void main(String[] args) {
        //正常业务中，这里面比较的是一个个对象
        AtomicStampedReference<Integer> atoInteger =
                new AtomicStampedReference<>(100, 1);
        new Thread(()->{
            int stamp = atoInteger.getStamp(); //获得版本号
            System.out.println("a1=>"+stamp);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("a2=>"+atoInteger.compareAndSet(100, 102,
                    atoInteger.getStamp(), atoInteger.getStamp() + 1));
            System.out.println("a3=>"+atoInteger.getStamp());

            System.out.println("a4=>"+atoInteger.compareAndSet(102, 100,
                    atoInteger.getStamp(), atoInteger.getStamp() + 1));
            System.out.println("a5=>"+atoInteger.getStamp());
        }, "a").start();

        new Thread(()->{
            int stamp = atoInteger.getStamp(); //获得版本号
            System.out.println("b1=>"+stamp);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("b2=>"+atoInteger.compareAndSet(100, 120,
                    stamp, stamp + 1));
            System.out.println("b3=>"+atoInteger.getStamp());
        }, "b").start();
    }
}
